package com.hspedu.homework.Homework03;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * @author DL5O
 * @version 1.0
 */
public class Homework03Client {
    public static void main(String[] args) throws Exception {
        String hostAddress = InetAddress.getLocalHost().getHostAddress();
        Socket socket = new Socket(hostAddress, 9999);

        System.out.println("成功连接上客服端..");
        //1.提示客户输入文件名
        String fileName ="";
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入文件名:");
        fileName = sc.next();

        //2.把客户输入的字符串（文件名）传给服务端
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write(fileName);
        bw.newLine();//表示写入结束，对方也需要容radLine来接受
        bw.flush();


        String filePath = "D:\\" + fileName +".mp3";
        //3.接受从客服端发来的文件
        InputStream is = socket.getInputStream();
        byte[] bytes = StreamUtils.streamToByteArray(is);
        //进行判断客服端是否有改文件
        if(bytes.length == 0 ) {
            System.out.println("没有该文件");
        }else{
            //有，则写入到对应的位置
            BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(filePath));
            bo.write(bytes,0, bytes.length);
            System.out.println("写入成功..");
            bo.close();
        }
        bw.close();
        System.out.println("客服端退出");
        socket.close();
    }
}
